-- 角色数据库
-- Author: Colocasia
-- Date: 2018-07-30
local log = require "log";

---@class db_character @玩家数据库类
---@field private redis_prefix string @数据缓存前缀
---@field private valid_time number @数据缓存有效期
local db_character = {}
local redis_prefix = 'characters:';
local valid_time = 3600;

---根据玩家GUID查找玩家
---@type fun(guid: string): table
---@param guid string
---@return table
function db_character:find_character_by_guid(guid)
    local key = redis_prefix.."guid_"..guid;
    local result = self:hgetall(key);
    if not result then
        result = self:characters_select_by_guid(guid);
    end

    self:expire_character(result);
    result = result and result[1];
    -- log.dump(result, "find_character_by_guid");
    return result;
end


---设置缓存有效期
---@param result character
function db_character:expire_character(result)
    if not result then return end
    for _, char in pairs(result) do
        local char_guid = char.guid
        self:expire(redis_prefix.."guid_"..char_guid, valid_time);
    end
end

return db_character;
